package com.nondo.rdp.finance.service.impl.log;

import com.nondo.rdp.auth.domain.Role;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.finance.domain.log.SignLog;
import com.nondo.rdp.finance.repository.log.SignLogRepository;
import com.nondo.rdp.finance.service.log.SignLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Transactional
@Service
public class SignLogServiceImpl implements SignLogService {
    @Autowired
    SignLogRepository signLogRepository;

    @Override
    public SignLog save(SignLog signLog) {
        return this.signLogRepository.save(signLog);
    }

    @Override
    public Page<SignLog> findAll(Page<SignLog> page, SignLog signLog) {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<SignLog> dictPage = signLogRepository.findAll((root, query, builder) -> {

            List<Predicate> predicates = new ArrayList<>();
            predicates.add(builder.like(root.get("delFlag"), Role.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<SignLog>(dictPage);
    }

    @Override
    public List<SignLog> findByUserAndCreateDateBetween(User user, Date createStartDate, Date createEndDate) {
        return this.signLogRepository.findByUserAndCreateDateBetween(user, createStartDate, createEndDate);
    }

    @Override
    public SignLog findByUserAndCreateDateAfter(User user, Date createStartDate) {
        return this.signLogRepository.findByUserAndCreateDateAfter(user, createStartDate);
    }
}